package com.futvan.z.framework.util;

import java.util.HashMap;
import java.util.Map;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.futvan.z.framework.common.bean.Code;
import com.futvan.z.framework.common.bean.Result;
import com.futvan.z.framework.core.z;

/**
 * 短信发送类
 * @author zj
 *
 */
public class SmsUtil {
	
	/**
	 * 发送手机验证码短信
	 * @param tel
	 * @param code
	 * @return
	 */
	public static Result SendCodeSMS(String tel,String code) {
		//通过阿里云短信接口发送
		Result result = aliyun_sms(tel,code);
		return result;
	}
	
	/**
	 * 阿里云短信接口
	 * 
	 * @author：administrator
	 * @Email：8888888@qq.com
	 * @CreationTime : 2017年2月20日
	 */
	private static Result aliyun_sms(String tel,String code){
		Result result = new Result();
		//AccessKeyId
		String AccessKeyId = "LTAIsephTEOkqaTs";
		//AccessKeySecret
		String AccessKeySecret = "qXdvzaqeRzzVXozUihPw00ebIUsGY1";
		//短信签名
		String SignName = "身份验证";
		//短信模板
		String TemplateCode = "SMS_49505009";
		
		DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", AccessKeyId, AccessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", tel);
        request.putQueryParameter("SignName", SignName);
        request.putQueryParameter("TemplateCode", TemplateCode);
        request.putQueryParameter("TemplateParam", "{\"code\":\""+code+"\",\"product\":\""+""+"\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            Map mapdata = JsonUtil.getObject(response.getData(), Map.class);
            if("OK".equals(mapdata.get("Code"))) {
            	result.setCode(Code.SUCCESS);
            	result.setMsg("发送成功");
            	z.Log("发送短信成功|"+tel+"|"+code);
            }else {
            	result.setCode(Code.ERROR);
            	result.setMsg(String.valueOf(mapdata.get("Message")));
            	z.Log("发送短信失败|"+tel+"|"+code+"|"+String.valueOf(mapdata.get("Message")));
            }
        } catch (Exception e) {
        	result.setCode(Code.ERROR);
        	result.setMsg(e.getMessage());
        }
        return result;
	}
}
